package controller

import (
	"github.com/labstack/echo"
	"net/http"

	"m-project-admin/app/entity"
	"m-project-admin/app/manager"
)

// 登录页面
func Login(c echo.Context) error {
	return c.Render(http.StatusOK, "login.html", nil)
}

// 登录接口
func DoLogin(c echo.Context) error {
	account := c.FormValue("account")
	password := c.FormValue("password")
	if account == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "账号不能为空"})
	}

	if password == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "密码不能为空"})
	}
	// 检查登录
	admin, isLogin, msg := manager.CheckLogin(account, password)

	if !isLogin {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: msg})
	}

	adminId := admin.Id.Hex()

	// 设置cookie
	manager.SetAdminCookie(&c, []byte(adminId))

	return c.JSON(http.StatusOK, entity.Response{En: 200, Em: "登录成功"})
}

// 退出接口
func Logout(c echo.Context) error {
	manager.DeleteAdminCookie(&c)
	return c.Redirect(http.StatusFound, "/login")
}
